package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
	"github.com/lab-online/pkg/util"
)

type searchUserReqQuery struct {
	Username string `form:"username" binding:"omitempty,min=1,max=10" example:"22080328"` // 学号
	Name     string `form:"name" binding:"omitempty,min=1,max=16" example:"姓名"`           // 姓名
	Role     uint8  `form:"role" binding:"omitempty,min=1,max=8" example:"1"`             // 角色
}

var SearchUserValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Query: &searchUserReqQuery{},
	}
})

type searchUserRespData struct {
	Username string `json:"username" binding:"required"` // 学号
	Name     string `json:"name" binding:"required"`     // 姓名
	Role     uint8  `json:"role" binding:"required"`     // 角色
}

type SearchUserRespBody struct {
	resp.BaseRespBody
	Data []searchUserRespData `json:"data" binding:"required"`
}

// SearchUser 搜素用户
//
//	@Summary				搜素用户
//	@Description			通过关键词搜索用户，支持学号、姓名、角色(查询所有老师、学生、管理员)
//	@Description.markdown	SearchUser
//	@Tags					user
//	@Accept					json
//	@Produce				json
//	@Security				bearer
//	@Param					Authorization	header		string				true	"`all`"
//	@Param					user			query		searchUserReqQuery	true	"用户信息"
//	@Success				200				{object}	SearchUserRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@x-apifox-status		"testing"
//	@Router					/v1/users/ [get]
func (h *Handler) SearchUser(c *gin.Context) {
	query := c.MustGet(mw.KeyQuery).(*searchUserReqQuery)

	queryEntity := entity.NewUserEntity(
		entity.WithUsername(query.Username),
		entity.WithName(query.Name),
		entity.WithRole(query.Role),
	)

	if users, err := h.domain.SearchUser(queryEntity); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Success(c, constant.CodeSuccessSearch, util.SliceMap(users,
			func(u entity.UserEntity) *searchUserRespData {
				return &searchUserRespData{
					Username: u.GetUsername(),
					Name:     u.GetName(),
					Role:     u.GetRole(),
				}
			},
		))
	}
}
